var PATH_PREFIX =ctx + 'business/prdSetup/standardPrjTemplate/';

var WASP_PRD_TEMPLATE = {
    addView: function() {
    	window.open(PATH_PREFIX + "addView.do");  
    },
    
    updateView: function(id) {
    	window.open(PATH_PREFIX + "updateView.do?id=" + id);  
    },

    deleteTemplate: function(id) {
    	/** 删除 */
		ctools.confirm({title : "确认删除？", text: ""},
		function(isConfirm){
			if(isConfirm){
				$.ajax({
					type : "POST",
					dataType : "json",
					url : PATH_PREFIX + "delete.do",
					cache: false,
					data: {
						id: id
					},
					success: function(data) {
						if (data.success) {
							swal(data.message, "", "success");
							queryByCondtion(false);
						} else {
							swal(data.message, "", "warning");
						}
					},
					error:function(xhr){
					   sweetAlertAjaxError(xhr);
					}
				});
			}
		});
    },

    detailView: function(id) {
        window.open(PATH_PREFIX + "detail.do?id=" + id);  
    },

    download: function(id) {
    	window.open(PATH_PREFIX + "download.do?id=" + id);
    },
    
    batchDownload: function(ids) {
    	var ids = $templateList.jqGrid('getGridParam','selarrrow');
    	if (ids.length == 0) {
    		toastr.warning('', '请先勾选需下载的数据');
    		return;
    	}
    	
    	//window.open(PATH_PREFIX + "download.do?ids=" + ids);
    	
    	post(PATH_PREFIX + "download.do", {
    		'id': ids
    	});
    },
    
};

// post 提交下载表单
function post(url, params) {
	var temp_form = document.createElement("form");      
	temp_form.action = url;
	temp_form.target = "_self";
	temp_form.method = "post";
	temp_form.style.display = "none";
	for (var x in params) {
		var opt = document.createElement("input");
	    opt.name = x;
	    opt.value = params[x];
	    temp_form.appendChild(opt);
	}
	document.body.appendChild(temp_form);
	temp_form.submit();
}

function formatUpdateTime(text, options, rData) {
	return moment(text).format('YYYY-MM-DD');
}

var $templateList = $('#templateList');
$(function() {
	$("#q-prdBizType").select2({ placeholder: '产品业务类型', width: '160px' });
	$("#q-prdCategory").select2({ placeholder: '产品分类', width: '160px' });
	$("#dept").select2({ placeholder: '部门' });
	
    $templateList.jqGrid({
        url: PATH_PREFIX+'standardPrjTemplateListPage.do',
//        caption: '标准理财产品模板列表',
        datatype: "json",
        colNames: ["ID", "模板名称", "产品分类", "产品业务类型", "更新时间", "附件数量",'操作'],
        colModel: [
            { name: 'id', index: 'id', hidden: true, key: true },
            { name: 'templateName', index: 'templateName', width: 60, resizable: true, sortable: false},
            { name: 'prdCategoryName', index: 'prdCategoryName', width: 30, resizable: true, sortable: false },
            { name: 'prdBizTypeName', index: 'prdBizTypeName', width: 25, resizable: true, sortable: false },
            { name: 'updateTime', index: 'updateTime', width: 25, resizable: true, sortable: false, formatter: formatUpdateTime },
            { name: 'attCount', index: 'attCount', hidden: true },
            { name: 'option', index: 'option', width: 20, resizable: true, sortable: false }
        ],
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        postData:{
		 	'sp[parentId]':'0'
			},  
        prmNames: {
        	        search: "search", 
        	        page: "pageNo",
        	        rows: "limit" 
        	       },
        height: 'auto',
        width: false,
        autowidth:true,
        shrinkToFit:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },
        multiselect: true,
        pager: "#templatePage",
        viewrecords: true,
        hidegrid: false,
		gridComplete: function() {
			var ids = $templateList.jqGrid('getDataIDs');
			for (var i = 0; i < ids.length; i++) {
                var id = ids[i];
                var rowData = $templateList.jqGrid('getRowData', id);
                var templateId = rowData.id;
	            var  detailBtn = '<a href="javascript:void(0);" class="btn btn-link btn-jqgrid" title="详情" onclick="WASP_PRD_TEMPLATE.detailView(\''+templateId+'\');">详情</a>';
	            var  downloadBtn = '<a href="javascript:void(0);" class="btn btn-link btn-jqgrid" title="下载" disabled>下载</a>';
	            debugger;
	            if (rowData.attCount > 0) {
	            	downloadBtn = '<a href="javascript:void(0);" class="btn btn-link btn-jqgrid" title="下载" onclick="WASP_PRD_TEMPLATE.download(\''+templateId+'\');">下载</a>';
	            }
	            
	            var params = {
					'templateUpdate' : 'templateUpdateTemp',
					'templateDelete': 'templateDeleteTemp'
				};
				var permissionButton = Permission_Button.configPermissionButton(params);
				permissionButton.templateUpdate = Permission_Button.clickPermissionButton('templateUpdateTemp','WASP_PRD_TEMPLATE.updateView(\''+templateId+'\');');
				permissionButton.templateDelete = Permission_Button.clickPermissionButton('templateDeleteTemp','WASP_PRD_TEMPLATE.deleteTemplate(\''+templateId+'\');');
	            
				$templateList.jqGrid('setRowData', ids[i], { option: detailBtn + '<span class="split"></span>' + downloadBtn + '<span class="split"></span>' +  Permission_Button.linkAllBtn(permissionButton)});
			}
		}
    });

    $templateList.navGrid('#templatePage', { edit: false, add: false, del: false, search: false, refreshstate: 'current' });
    $templateList.jqGrid('setFrozenColumns');
    jqGridResize($templateList);
    
    //注册清空事件
    WASP_WIDGET.registerResetClearEvent();
    
});




/**
 * 通过条件进行搜索
 */
function queryByCondtion(flag) {
    var templateName = $("#q-templateName").val();
    templateName = $.trim(templateName);
    var prdBizType = $("#q-prdBizType").val();
    var prdCategory = $("#q-prdCategory").val();
    
    var postData = $templateList.jqGrid("getGridParam", "postData");
	$.extend(postData, {
		'sp[templateName]':templateName,
		'sp[prdBizType]':prdBizType,
		'sp[prdCategory]':prdCategory
	});
    if (flag) {
    	$templateList.trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
    } else {
    	$templateList.trigger("reloadGrid"); //重新载入Grid表格
    }
};
